package com.iflytek.jcy.supervise.job.component.permission;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.dev33.satoken.exception.DisableServiceException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SaTokenException;
import com.iflytek.jcy.supervise.job.common.enums.ResultEnum;
import com.iflytek.jcy.supervise.job.common.pojo.CommonResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 授权全局异常处理
 * <p>
 * 当出现授权校验不通过而抛出异常时, 返回异常响应
 */
@ControllerAdvice
public class SaTokenExceptionHandler {

    /**
     * 全局异常拦截（拦截项目中的所有异常）
     */
    @ResponseBody
    @ExceptionHandler({SaTokenException.class})
    public CommonResponse handlerException(Exception e, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        if (e instanceof NotLoginException) {    // 如果是未登录异常
            NotLoginException ee = (NotLoginException) e;
            return CommonResponse.failed(ResultEnum.LOGIN_REQUIRED);
        }
        else if (e instanceof NotRoleException) {        // 如果是角色异常
            NotRoleException ee = (NotRoleException) e;
            return CommonResponse.failed(ResultEnum.ROLE_MISSING, "当前用户无此角色：" + ee.getRole());
        }
        else if (e instanceof NotPermissionException) {    // 如果是权限异常
            NotPermissionException ee = (NotPermissionException) e;
            return CommonResponse.failed(ResultEnum.PERMISSION_MISSING, "当前用户无此权限：" + ee.getCode());
        }
        else if (e instanceof DisableServiceException) {    // 如果是被封禁异常
            DisableServiceException ee = (DisableServiceException) e;
            return CommonResponse.failed(ResultEnum.DISABLED_ERROR, "账号被封禁：" + ee.getDisableTime() + "秒后解封");
        }
        else {
            throw e;
        }
    }

}